package com.bsb.biz.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.bsb.base.common.util.BeanUtils;
import com.bsb.base.common.util.DateUtils;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.model.Answer;
import com.bsb.base.model.AnswerUser;
import com.bsb.base.model.BsbRapid;
import com.bsb.base.model.BsbRapidAnswer;
import com.bsb.base.model.BsbRapidAnswerExample;
import com.bsb.base.model.BsbRapidAnswerExample.Criteria;
import com.bsb.base.model.BsbUser;
import com.bsb.base.model.Rapid;
import com.bsb.biz.service.BsbRapidAnswerService;
import com.bsb.biz.service.BsbRapidService;
import com.bsb.biz.service.BsbUserService;
import com.bsb.biz.shiro.UserUtils;

@Controller
@RequestMapping("/bsbRapid")
public class BsbRapidController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/bsbRapid/list.do";
	
	@Resource
	private BsbRapidService bsbRapidService;
	@Resource
	private BsbUserService bsbUserService;
	@Resource
	private BsbRapidAnswerService bsbRapidAnswerService;
	
/*	@RequiresPermissions("bsbRapid:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,String createDate,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		BsbRapidExample bsbRapidExample = new BsbRapidExample();
		Criteria criteria = bsbRapidExample.createCriteria();
		if(StringUtils.isNotEmpty(createDate)){
			String beginStr = createDate + " 00:00:00";
			String endStr = createDate + " 23:59:59";
			Date beginDate = DateUtils.parseDate(beginStr);
			Date endDate = DateUtils.parseDate(endStr);
			criteria.andCreateDateGreaterThanOrEqualTo(beginDate);
			criteria.andCreateDateLessThanOrEqualTo(endDate);
		}
		int totalCount = bsbRapidService.countBsbRapid(bsbRapidExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		bsbRapidExample.setPageIndex((pageNum - 1) * pageSize);
		bsbRapidExample.setPageSize(pageSize);
		bsbRapidExample.setOrderByClause("createDate DESC");
		List<BsbRapid> bsbRapids = bsbRapidService.getPageBsbRapid(bsbRapidExample);
		for (BsbRapid bsbRapid : bsbRapids) {
			String userId = bsbRapid.getUserId();
			BsbUser bsbUserByUuid = bsbUserService.getBsbUserByUuid(userId);
			if(null != bsbUserByUuid){
				bsbRapid.setUserId(bsbUserByUuid.getName());
			}
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("bsbRapids", bsbRapids);
		model.addAttribute("createDate", createDate);
		return "/BsbRapid/list";
	}*/
	
	@RequiresPermissions("bsbRapid:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,@RequestParam Map<String, Object> params,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		String question = (String) params.get("question");
		String firm = (String) params.get("firm");
		String uuid = (String) params.get("uuid");
		String qname = (String) params.get("qname");
		String status = (String) params.get("status");
		String aname = (String) params.get("aname");
		String start = (String) params.get("start");
		Date startDate = DateUtils.parseDate(start);
		
		String end = (String) params.get("end");
		Date endDate = DateUtils.parseDate(end);
		
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT DISTINCT")
		   .append("  (r.`uuid`),")
		   .append("  r.`userId` quserid,")
		   .append("  u.`name` qusername,")
		   .append("  ra.`userId` auserid,")
		   .append("  au.`name` ausername,")
		   .append("  r.`content`,")
		   .append("  r.`createDate`,")
		   .append("  r.`status`,")
		   .append("  r.`price`")
		   .append(" FROM")
		   .append("  bsb_rapid r")
		   .append("  LEFT JOIN bsb_rapid_answer ra")
		   .append("    ON r.`uuid` = ra.`rapidId`")
		   .append("  LEFT JOIN bsb_user u")
		   .append("    ON u.`uuid` = r.`userId`")
		   .append(" LEFT JOIN bsb_user au ")
		   .append("    ON au.`uuid` = ra.`userId`")
		   .append("  LEFT JOIN bsb_firm f")
		   .append("    ON f.`account` = ra.`firmId`")
		   .append("    WHERE 1 = 1 ");
		if(StringUtils.isNotEmpty(question)){
			sql.append(" AND r.`content` LIKE concat(concat('%','"+question+"'),'%')");
		}
		if(StringUtils.isNotEmpty(firm)){
			sql.append("  AND f.`name` LIKE concat(concat('%','"+firm+"'),'%')");
		}
		if(StringUtils.isNotEmpty(uuid)){
			sql.append(" AND r.`uuid` = '"+uuid+"'");
		}
		if(StringUtils.isNotEmpty(qname)){
			sql.append(" AND u.`name` LIKE concat (concat ('%', '"+qname+"'), '%')");
		}
		if(StringUtils.isNotEmpty(status)){
			sql.append(" AND r.`status` = '"+status+"'");
		}
		if(StringUtils.isNotEmpty(aname)){
			sql.append(" AND au.`name` LIKE concat (concat ('%', '"+aname+"'), '%')");
		}
		if(null != startDate){
			start = DateUtils.formatDate(startDate, "yyyy-MM-dd");
			sql.append(" AND r.`createDate` >= concat('"+start+"',' 00:00:00')");
		}
		if(null != endDate){
			end = DateUtils.formatDate(endDate, "yyyy-MM-dd");
			sql.append(" AND r.`createDate` <= concat('"+end+"',' 23:59:59')");
		}
		Long firmId = UserUtils.currentUser().getFirmId();
		if(firmId != 10000){
			sql.append(" AND ra.`firmId`='"+firmId+"'");
			sql.append(" AND ra.`userId` IS NOT NULL");
		}
		sql.append(" GROUP BY r.`uuid`");
		int totalCount = bsbRapidService.countRapid(sql.toString());
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		sql.append(" ORDER BY r.`createDate` DESC");
		sql.append(" LIMIT "+(pageNum - 1) * pageSize+","+pageSize+"");
		List<Rapid> bsbRapids = bsbRapidService.selectPageRapid(sql.toString());
		for (Rapid rapid : bsbRapids) {
			String rid = rapid.getUuid();
			List<AnswerUser> answerUsers = bsbRapidAnswerService.getAnswerUsers(rid);
			rapid.setAnswerLists(answerUsers);
			BsbRapidAnswer adoptUser = bsbRapidAnswerService.getadoptUser(rid);
			String userId = adoptUser.getUserId();
			rapid.setAdoptuserid(userId);
			rapid.setAdoptusername(bsbUserService.getUserNameById(userId));
			rapid.setAdoptuserdept(bsbUserService.getFirmByUserId(userId).getName());
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("bsbRapids", bsbRapids);
		model.addAttribute("question", question);
		model.addAttribute("firm", firm);
		model.addAttribute("uuid", uuid);
		model.addAttribute("qname", qname);
		model.addAttribute("status", status);
		model.addAttribute("aname", aname);
		model.addAttribute("start", start);
		model.addAttribute("end", end);
		return "/BsbRapid/list";
	}
	
	@RequiresPermissions("bsbRapid:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		return "/BsbRapid/add";
	}

	@RequiresPermissions("bsbRapid:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String add(Model model, @ModelAttribute("bsbRapid") BsbRapid bsbRapid) {
		bsbRapidService.addBsbRapid(bsbRapid);
		return redirect;
	}
	
	@RequiresPermissions("bsbRapid:delete")
	@RequestMapping(value = "/{uuid}/delete", method = RequestMethod.GET)
	public String del(Model model,
			@PathVariable("uuid") String uuid) {
		bsbRapidService.delBsbRapidByUuid(uuid);
		return redirect;
	}
	
	@RequiresPermissions("bsbRapid:update")
	@RequestMapping(value = "/{uuid}/update", method = RequestMethod.GET)
	public String toEdit(Model model,
			@PathVariable("uuid") String uuid) {
		BsbRapid bsbRapid = bsbRapidService.getBsbRapidByUuid(uuid);
		model.addAttribute("bsbRapid", bsbRapid);
		return "/BsbRapid/edit";
	}

	@RequiresPermissions("bsbRapid:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String edit(Model model, @ModelAttribute("bsbRapid") BsbRapid bsbRapid) {
		bsbRapidService.updateBsbRapid(bsbRapid);
		return redirect;
	}
	
	@RequiresPermissions("bsbRapid:view")
	@RequestMapping(value = "/{uuid}/view", method = RequestMethod.GET)
	public String view(Model model,
			@PathVariable("uuid") String uuid) {
		BsbRapid bsbRapid = bsbRapidService.getBsbRapidByUuid(uuid);
		String quUserId = bsbRapid.getUserId();
		BsbUser user = bsbUserService.getBsbUserByUuid(quUserId);
		if(null != user){
			bsbRapid.setUserId(user.getName());
		}
		BsbRapidAnswerExample example = new BsbRapidAnswerExample();
		com.bsb.base.model.BsbRapidAnswerExample.Criteria criteria = example.createCriteria();
		criteria.andRapidIdEqualTo(uuid);
		example.setOrderByClause("ansDate DESC");
		List<Answer> answers = new ArrayList<Answer>();
		List<BsbRapidAnswer> rapidanswers = bsbRapidAnswerService.selectByExample(example );
		for (BsbRapidAnswer bsbRapidAnswer : rapidanswers) {
			Answer answer = new Answer();
			BeanUtils.copyProperties(answer, bsbRapidAnswer);
			String userId = bsbRapidAnswer.getUserId();
			BsbUser bsbUserByUuid = bsbUserService.getBsbUserByUuid(userId);
			if(null != bsbUserByUuid){
				answer.setAnswerName(bsbUserByUuid.getName());
				answer.setRoleName(bsbUserByUuid.getRole());
			}
			answers.add(answer);
		}
		model.addAttribute("answers", answers);
		model.addAttribute("bsbRapid", bsbRapid);
		return "/BsbRapid/view";
	}
}
